import {NgModule,Directive,EventEmitter,ElementRef,AfterViewInit,OnInit,OnDestroy,HostListener,Input,Output,TemplateRef, ViewContainerRef} from '@angular/core';
import {DomHandler} from '../dom/domhandler';
import {CommonModule} from '@angular/common';
import { StorageService } from '../../common/storage.service';

import { Subject } from 'rxjs/Subject';

@Directive({
    selector: '[pButton]',
    providers: [DomHandler]
})
export class Button implements AfterViewInit, OnInit, OnDestroy {

    @Input() iconPos: string = 'left';

    @Input() permission: string;

    @Input() debounceTime: number = 500;

    @Input() cornerStyleClass: string = 'ui-corner-all btn';

    @Output() deClick = new EventEmitter();



    public _label: string;

    public _icon: string;

    public initialized: boolean;

    private clicks = new Subject();

    private subscription: any;

    constructor(public el: ElementRef, public domHandler: DomHandler,public rights:StorageService) {}

    ngOnInit(){
        this.el.nativeElement.style.display = 'none';
        this.subscription = this.clicks
            .debounceTime(this.debounceTime)
            .subscribe(e => this.deClick.emit(e));
    }

    ngAfterViewInit() {
        if(this.permission){
            this.rights.getRights().then(data=>{
               let right = data.btnRight(this.permission)
               
               if(right){this.initEle();return}
               this.removeThis()
            })
        }else{
          this.initEle()
        }

    }

    initEle(){
        this.domHandler.addMultipleClasses(this.el.nativeElement, this.getStyleClass());
        if(this.icon) {
            let iconElement = document.createElement("span");
            let iconPosClass = (this.iconPos == 'right') ? 'ui-button-icon-right': 'ui-button-icon-left';
            iconElement.className = iconPosClass  + ' ui-clickable fa fa-fw ' + this.icon;
            this.el.nativeElement.appendChild(iconElement);
        }

        let labelElement = document.createElement("span");
        labelElement.className = 'ui-button-text ui-clickable';
        labelElement.appendChild(document.createTextNode(this.label||'ui-btn'));
        this.el.nativeElement.appendChild(labelElement);
        this.initialized = true;
        this.el.nativeElement.style.display = 'initial'
    }

    @HostListener('click', ['$event'])
    clickEvent(event) {
      this.clicks.next(event);
    }

    removeThis(){
        this.el.nativeElement.parentNode.removeChild(this.el.nativeElement)
    }

    getStyleClass(): string {
        let styleClass = 'ui-button ui-widget ui-state-default ' + this.cornerStyleClass;
        if(this.icon) {
            if(this.label != null && this.label != undefined) {
                if(this.iconPos == 'left')
                    styleClass = styleClass + ' ui-button-text-icon-left';
                else
                    styleClass = styleClass + ' ui-button-text-icon-right';
            }
            else {
                styleClass = styleClass + ' ui-button-icon-only';
            }
        }
        else {
            styleClass = styleClass + ' ui-button-text-only';
        }

        return styleClass;
    }

    @Input() get label(): string {
        return this._label;
    }

    set label(val: string) {
        this._label = val;

        if(this.initialized) {
            this.domHandler.findSingle(this.el.nativeElement, '.ui-button-text').textContent = this._label;
        }
    }

    @Input() get icon(): string {
        return this._icon;
    }

    set icon(val: string) {
        this._icon = val;

        if(this.initialized) {
            let iconPosClass = (this.iconPos == 'right') ? 'ui-button-icon-right': 'ui-button-icon-left';
            this.domHandler.findSingle(this.el.nativeElement, '.fa').className =
                iconPosClass + ' ui-clickable fa fa-fw ' + this.icon;
        }
    }

    ngOnDestroy() {
        while(this.el.nativeElement.hasChildNodes()) {
            this.el.nativeElement.removeChild(this.el.nativeElement.lastChild);
        }
        this.subscription.unsubscribe();
        this.initialized = false;
    }
}

@Directive({
    selector: '[pDebounce]'
})

export class Debounce implements OnInit, OnDestroy{

    @Input() debounceTime: number = 500;

    @Output() deClick = new EventEmitter();

    private clicks = new Subject();
    
    private subscription: any;

    ngOnInit() {
        this.subscription = this.clicks
        .debounceTime(this.debounceTime)
        .subscribe(e => this.deClick.emit(e));
    }

    @HostListener('click', ['$event'])
      clickEvent(event) {
        this.clicks.next(event);
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}


// @Directive({
//     selector: '[permission]'
// })

// export class Permission {
    
//     constructor(private templateRef: TemplateRef<any>,private viewContainer: ViewContainerRef,private rights:StorageService){}

//     @Input('permission')  set permission(permis: boolean) {
//         if (!permis) {       
//             this.viewContainer.createEmbeddedView(this.templateRef);     
//         } else {
//             this.rights.getRights().then(data => {
                
//                     let right = data.btnRight(permis)
//                     if (right)
//                         this.viewContainer.createEmbeddedView(this.templateRef)
//                     else
//                         this.viewContainer.clear();
//                 })            
//             }  
//         }
//     }

@NgModule({
    imports: [CommonModule],
    exports: [Button,Debounce],
    declarations: [Button,Debounce]
})
export class ButtonModule { }
